package dao

import (
	"context"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"time"
)

type Article struct {
	ID      int    `gorm:"primaryKey,autoIncrement"`
	Title   string `gorm:"colunm:title"`
	Content string `gorm:"colunm:content"`
	Writter string `gorm:"colunm:witter"`
	Ctime   int64  `gorm:"colunm:ctime"`
	Utime   int64  `gorm:"colunm:utime"`
}

type ArticleDao interface {
	Insert(ctx context.Context, article Article) (int, error)
	Update(ctx context.Context, article Article) error
	Save(ctx context.Context, article Article) error
}

type articleDao struct {
	db *gorm.DB
}

func NewArticleDao(db *gorm.DB) ArticleDao {
	db.AutoMigrate(&Article{})
	return &articleDao{
		db: db,
	}
}

func (a *articleDao) Save(ctx context.Context, article Article) error {
	return a.db.WithContext(ctx).
		Clauses(clause.OnConflict{
			DoUpdates: clause.AssignmentColumns([]string{"utime", "content", "title"}),
		}).Create(article).Error
}

func (a *articleDao) Insert(ctx context.Context, article Article) (int, error) {
	//TODO implement me
	Utime := time.Now().Unix()
	Ctime := time.Now().Unix()
	article.Ctime = Ctime
	article.Utime = Utime
	err := a.db.WithContext(ctx).Create(&article).Error
	return article.ID, err
}

func (a *articleDao) Update(ctx context.Context, article Article) error {
	return a.db.WithContext(ctx).Updates(&article).Error
}
